﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Hos.ScheduleMaster.Base;
using System.Reflection;
using System.Net.Http;

namespace NFinal.Common.TaskLogger
{
    public class ScheduleMasterLogger : ITaskLogger
    {
        public string Name { get; }
        public TaskContext context;
        public CancellationToken CancellationToken { get; }
        public ScheduleMasterLogger(TaskContext context,string name)
        {

            this.context = context;
            Type type = context.GetType();
            FieldInfo instanceField = type.GetField("_instance", BindingFlags.NonPublic | BindingFlags.Instance);//获得私有字段
            var taskBase=(TaskBase)instanceField.GetValue(context);
            this.CancellationToken = taskBase.CancellationToken;
            if (name == null)
            {
                this.Name = taskBase.TaskId.ToString();
            }
            else
            {
                this.Name = name;
            }
        }

        public void LogError(string error)
        {
            context.WriteLog($"任务{Name}:"+error, Hos.ScheduleMaster.Base.Dto.LogCategory.Error);
        }

        public void LogExp(Exception ex)
        {
            context.WriteError(ex);
        }

        public void LogExp(Exception ex, string message)
        {
            context.WriteLog($"任务{Name}:" + message, Hos.ScheduleMaster.Base.Dto.LogCategory.Error);
        }

        public void LogInfo(string message)
        {
            context.WriteLog($"任务{Name}:" + message, Hos.ScheduleMaster.Base.Dto.LogCategory.Info);
        }
        public void LogWarn(string warn)
        {
            context.WriteLog($"任务{Name}:" + warn, Hos.ScheduleMaster.Base.Dto.LogCategory.Warn);
        }
        public void LogPercentage(double percentage, string name = null)
        {
            context.WriteLog($"任务{Name}:当前进度{percentage}%",Hos.ScheduleMaster.Base.Dto.LogCategory.Info);
        }

        public bool CancelCurrentTask()
        {
            return false;
        }
    }
}
